<?php

class AdminMemberController extends BaseController
{
    public $memberObj;
    public function __construct()
    {
        parent::__construct();
        $this->memberObj = new Member();
        $this->treeModel = new TreeModel();
    }

    public function AddAction()
    {
        $tree = $this->treeModel->orderBy('L','asc')->select();
        $list = [];
        foreach ($tree as $item) {
            $list[$item['pid']][] = $item;
        }
        $this->assign('tree', $list);

        $css = [
            '/Statics/css/add.css'
        ];
        $this->assign('css', $css);

        $this->display();
    }

    public function AjaxSaveAction()
    {
        $data = $_POST;

        switch ($data['op']) {
            case 1:
                //删除
                $currNode = $this->_getNodeById($data['id']);
                $num = $currNode['R'] - $currNode['L'] + 1;
                $this->treeModel->where(['L'=>['>=',$currNode['L']], 'R'=>['<=',$currNode['R']]])->delete();
                $this->treeModel->where(['L'=>['>',$currNode['R']]])->update(['L'=>"L-{$num}"]);
                $this->treeModel->where(['R'=>['>',$currNode['R']]])->update(['R'=>"R-{$num}"]);
                break;
            case 2:

                //交换两节点位置
                $currNode = $this->_getNodeById($data['id']);
                $num = $currNode['R'] - $currNode['L'] + 1;
                $chgNode = $this->_getNodeById($data['id2']);
                $num2 = $chgNode['R'] - $chgNode['L'] + 1;
                $this->treeModel->execute('UPDATE `tree` SET dorder=IF(dorder=' . $currNode['dorder'] . ',' . $chgNode['dorder'] . ',' . $currNode['dorder'] . ') WHERE id IN(' . $data['id'] . ',' . $data['id2'] . ')');
                $sql = 'UPDATE `tree` 
                    SET L=L+IF(L>' . $currNode['R'] . ',-' . $num . ',' . $num2 . '), R=R+IF(R>' . $currNode['R'] . ',-' . $num . ',' . $num2 . ') 
                    WHERE (L>=' . $currNode['L'] . ' AND R<=' . $currNode['R'] . ') OR (L>=' . $chgNode['L'] . ' AND R<=' . $chgNode['R'] . ')';
                $this->treeModel->execute($sql);
                break;
            case 3:
                //移动
                $currNode = $this->_getNodeById($data['id']);
                $pNode = $this->_getNodeById($data['pid']);
                $num = $currNode['R'] - $currNode['L'] + 1;
                $maxR = $this->treeModel->field('MAX(R)')->get();
                //把节点放到maxR最后用来暂存LR
                $lastMaxR = $maxR - $currNode['L'] + 1;
                $this->treeModel->where(['L'=>['>=',$currNode['L']],'R'=>['<=',$currNode['R']]])->update(['L'=>'L+'.$lastMaxR,'R'=>'R+'.$lastMaxR]);
                if($pNode){
                    //调整节点后的LR值
                    if($currNode['R']<$maxR){
                        $this->treeModel->where(['L'=>['<=',$currNode['R']],'L'=>['<=',$maxR]])->update(['L'=>'L-'.$num]);
                        $this->treeModel->where(['R'=>['>=',$currNode['R']],'L'=>['<=',$maxR]])->update(['R'=>'R-'.$num]);
                    }
                    //纠正从前移到后的pnode的LR值
                    if($pNode['L']>$currNode['L']){
                        $pNode['R'] -= $num;
                    }
                    $this->treeModel->where(['L'=>['<=',$pNode['R']],'L'=>['<=',$maxR]])->update(['L'=>'L+'.$num]);
                    $this->treeModel->where(['R'=>['>=',$pNode['R']],'L'=>['<=',$maxR]])->update(['R'=>'R+'.$num]);

                    //把暂存节点LR放到父节点腾出的LR值空间
                    $pNodeR=-$maxR + $pNode['R']-1;
                    $this->treeModel->where(['L'=>['>',$maxR]])->update(['L'=>'L+'.$pNodeR,'R'=>'R+'.$pNodeR]);
                }else{
                    $this->treeModel->where(['L'=>['>',$currNode['R']]])->update(['L'=>'L-'.$num]);
                    $this->treeModel->where(['R'=>['>=',$currNode['R']]])->update(['R'=>'R-'.$num]);
                }

                break;
            case 4:
                //添加
                $pNode = $this->_getNodeById($data['pid']);
                $this->treeModel->where(['L'=>['>',$pNode['R']]])->update(['L'=>"L+2"]);
                $this->treeModel->where(['R'=>['>=',$pNode['R']]])->update(['R'=>"R+2"]);
                $this->treeModel->insert(['pid'=>$data['pid'],'name'=>addslashes($data['name']),'L'=>$pNode['R'],'R'=>($pNode['R']+1)]);
                $id = $this->treeModel->getInsertId();
                $this->treeModel->where(['id'=>$id])->update(['dorder'=>$id]);
                break;
        }
        $ret = array(
            'code' => 0,
            'msg'=>'',
            //'data'   => [],
        );
        $this->AjaxReturn($ret);
    }

    private function _getNodeById($id)
    {
        if($id){
            $node = $this->treeModel->where(['id' => $id])->field('L,R,dorder')->get();
            return $node;
        }
        return [];
    }

    public function EditAction()
    {
        $member = $this->treeModel->where(['id'=>$_GET['id']])->get();
        $parent = $this->treeModel->where(['id'=>$member['pid']])->get();
        if(empty($member['dad'])){
            $member['dad'] = isset($parent['name'])?$parent['name']:'';
        }
        if(empty($member['mother'])){
            $member['mother'] = isset($parent['wname'])?$parent['wname']:'';
        }
        if(empty($member['nation'])){
            $member['nation'] = '中国';
        }

        $this->assign('member', $member);
        //长幼次序
        $rankList = $this->memberObj->getRankList();
        $this->assign('rankList', $rankList);
        //家中排行
        $familySort = $this->memberObj->getFamilySort();
        $this->assign('familySort', $familySort);

        //辈分
        $zibeiList = (new ZibeiModel())->select();
        $this->assign('zibeiList', $zibeiList);

        //兄弟姐妹
        $brother = $sisters = '';
        if(empty($member['pid'])){
            $brother = '未知';
            $sisters = '未知';
        }else{
            $member1 =$this->treeModel->where(['pid' => $member['pid'],'id'=>['<>',$member['id']]])->select('name,sex');
            foreach ($member1 as $item) {
                if ($item['name'] != $member['name']) {
                    if ($item['sex'] == '男') {
                        $brother .= $item['name'] . '、';
                    } elseif ($item['sex'] == '女') {
                        $sisters .= $item['name'] . '、';
                    }
                }
            }
            $brother = $brother ? mb_substr($brother,0,-1) : '无';
            $sisters = $sisters ? mb_substr($sisters,0,-1) : '无';
        }
        $this->assign('brother', $brother);
        $this->assign('sisters', $sisters);

        //子女
        $son = $daughter = '';
        $member1 =$this->treeModel->where(['pid' => $member['id']])->select('name,sex');
        foreach ($member1 as $item) {
            if ($item['sex'] == '男') {
                $son .= $item['name'] . '、';
            } elseif ($item['sex'] == '女') {
                $daughter .= $item['name'] . '、';
            }
        }

        $son = $son ? mb_substr($son,0,-1) : '无';
        $daughter = $daughter ? mb_substr($daughter,0,-1) : '无';
        $this->assign('son', $son);
        $this->assign('daughter', $daughter);

        $this->display();
    }

    public function UpdateAction()
    {
        $data = $_POST;
        if(empty($data['marriage'])){
            if($data['wname']){
                $data['marriage'] = '已婚';
            }else{
                $data['son'] = '无';
                $data['daughter'] = '无';
            }
        }
        if(isset($data['tongxun']) && $data['tongxun'] && substr($data['tongxun'],0,2)!=='##'){
            $data['tongxun'] = '##'.Aes::encrypt($data['tongxun']);
        }

        $this->treeModel->where(['id' => $data['id']])->update($data);
        //关联修改
        //1.父辈
        $this->_updateParent($data['pid']);
        //2.平辈
        $this->_updateEqual($data['pid'],$data['id']);
        //3.子女
        $this->_updateChildren($data['id'],$data);

        $this->memberObj->getBiography($data['id'],true);
        $this->redirect('/Admin/Member/Edit?id=' . $data['id']);
    }

    private function _updateParent($id){
        if($id){
            $son = $daughter = '';
            $member1 =$this->treeModel->where(['pid' => $id])->select('name,sex');
            foreach ($member1 as $item) {
                if ($item['sex'] == '男') {
                    $son .= $item['name'] . '、';
                } elseif ($item['sex'] == '女') {
                    $daughter .= $item['name'] . '、';
                }
            }

            $son = $son ? mb_substr($son,0,-1) : '无';
            $daughter = $daughter ? mb_substr($daughter,0,-1) : '无';
            $this->treeModel->where(['id' => $id])->update(['son'=>$son,'daughter'=>$daughter]);
            $this->memberObj->getBiography($id,true);
        }
    }
    private function _updateEqual($pid,$id){
        $member = $this->treeModel->where(['pid' => $pid,'id'=>['<>',$id]])->select('id,name,sex');

        foreach ($member as $item) {
            $brother = $sisters = '';
            $member2 = $this->treeModel->where(['pid' => $pid])->select('id,name,sex');
            foreach ($member2 as $item2) {
                if ($item2['id'] != $item['id']) {
                    if ($item2['sex'] == '男') {
                        $brother .= $item2['name'] . '、';
                    } elseif ($item2['sex'] == '女') {
                        $sisters .= $item2['name'] . '、';
                    }
                }
            }

            $brother = $brother ? mb_substr($brother,0,-1) : '无';
            $sisters = $sisters ? mb_substr($sisters,0,-1) : '无';

            $this->treeModel->where(['id' => $item['id']])->update(['brother'=>$brother,'sisters'=>$sisters]);
            $this->memberObj->getBiography($item['id'],true);
        }
    }

    private function _updateChildren($id,$data){

        $member = $this->treeModel->where(['pid' => $id])->select('id,name,sex');
        foreach ($member as $item) {
            $this->treeModel->where(['id' => $item['id']])->update(['dad'=>$data['name'],'mother'=>$data['wname']]);
            $this->memberObj->getBiography($item['id'],true);
        }
    }
}
